package thulearningcore.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TLURLEncoder {

	private static String zhPattern = "[\u4e00-\u9fa5]+";

	/**
	 * encode string
	 * 
	 * @param str
	 *            string to replace
	 * @param charset
	 *            charset
	 * @return replaced string
	 * @throws UnsupportedEncodingException
	 * 
	 */
	public static String encode(String str, String charset)
			throws UnsupportedEncodingException {
		Pattern p = Pattern.compile(zhPattern);
		Matcher m = p.matcher(str);
		StringBuffer b = new StringBuffer();
		while (m.find()) {
			m.appendReplacement(b, URLEncoder.encode(m.group(0), charset));
		}
		m.appendTail(b);
		return b.toString();
	}
}
